package com.bimiaomiao.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONPObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bimiaomiao.Application;
import com.bimiaomiao.entity.ClientModelConfig;
import com.bimiaomiao.entity.ProgramInfo;
import com.bimiaomiao.entity.RequestCollection;
import com.bimiaomiao.service.IRequestCollectionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import java.io.Console;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/request")
@Api("请求收集")
public class FiddlerRequestController {

    @Autowired
    private ClientModelConfig clientModelConfig;

    @PostMapping("/collect")
    @ApiOperation(value = "请求接口抓取", notes = "请求接口抓取.")
    public String collect(@RequestBody MultiValueMap<String, String> result) {
        if(clientModelConfig==null)
        {
            System.out.println("客户端-模块未设置");
            return "客户端-模块未设置";
        }
        if(clientModelConfig.isOpen()==false)
        {
            System.out.println("未开启抓取");
            return "未开启抓取";
        }
        if(clientModelConfig.getClientName()==null || clientModelConfig.getClientName().equals(""))
        {
            System.out.println("客户端名称未设置");
            return "客户端名称未设置";
        }

        if(clientModelConfig.getUiName()==null || clientModelConfig.getUiName().equals(""))
        {
            System.out.println("界面名未设置");
            return "界面名未设置";
        }
        if(clientModelConfig.getActionName()==null || clientModelConfig.getActionName().equals(""))
        {
            System.out.println("操作名未设置");
            return "操作名未设置";
        }

        System.out.println("当前准备写入:客户端:"+clientModelConfig.getClientName()+","
                +"页面UI:"+clientModelConfig.getUiName()+",操作:"+clientModelConfig.getActionName());
        RequestCollection requestCollection = new RequestCollection();
        requestCollection.setClientName(clientModelConfig.getClientName());
        requestCollection.setUiName(clientModelConfig.getUiName());
        requestCollection.setActionName(clientModelConfig.getActionName());


        if (result.size() == 4) {
            String path = "";
            //StringBuilder logBuilder = new StringBuilder("请求开始--------\n");
            for (Map.Entry<String, List<String>> stringListEntry : result.entrySet()) {
                if (result.get("url").size() > 0) {
                    String url = result.get("url").get(0);
                    //logBuilder.append("url::::" + url + "\n");
                    requestCollection.setUrl(url);
                }
                if (result.get("headers").size() > 0) {
                    String headers = result.get("headers").get(0);

                    //logBuilder.append("headers::::" + headers + "\n");
//                    requestCollection.setInParam(headers);
                }
                if (result.get("form").size() > 0) {
                    String form = result.get("form").get(0);
                    if(!form.equals("")&&form!=null)
                    {
                        ProgramInfo programInfo = JSON.parseObject(form, ProgramInfo.class);
                        if(programInfo==null) programInfo = new ProgramInfo();
                        requestCollection.setUniqueKey(programInfo.getUniqueKey());
                        requestCollection.setMethodName(programInfo.getMethodName());
                    }
                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher m = p.matcher(form);
                    String destIn = m.replaceAll("");
//                    logBuilder.append("form:::" + form + "\n");
                    requestCollection.setInParam(destIn);
                    System.out.println(destIn);
                }
                if (result.get("result").size() > 0) {
                    String tmp = result.get("result").get(0);
                    //将前端替换的字符转回为&
                    tmp = tmp.replace("--$4*9$--","&");
//                    logBuilder.append("result::::" + result1 + "\n");
                    Pattern p = Pattern.compile("\\s*|\t|\r|\n");
                    Matcher m = p.matcher(tmp);
                    String destOut = m.replaceAll("");
                    requestCollection.setOutParam(destOut);
                }

                path = requestCollection.getUniqueKey()+"-"+requestCollection.getMethodName();
                System.out.println("进入,"+path);
            }

            if(requestCollection.getOutParam()!=null && !requestCollection.getOutParam().equals(""))
            {
                //如果unique_key  method_name client_name model_name相同,则不插入
                QueryWrapper<RequestCollection> wrapper = new QueryWrapper<>();
                wrapper.eq("unique_key", requestCollection.getUniqueKey());
                wrapper.eq("method_name",requestCollection.getMethodName());
                wrapper.eq("client_name",requestCollection.getClientName());
                wrapper.eq("ui_name",requestCollection.getUiName());
                wrapper.eq("action_name",requestCollection.getActionName());

                int count = collectionService.count(wrapper);
                if(count==0)
                {
                    collectionService.save(requestCollection);
                    System.out.println("采集保存,"+path);
                }
                else
                {
                    System.out.println("已采集过,放弃保存,"+path);
                }

            }
            else
            {
                System.out.println("出参不满足,退出,"+path);
            }
//            logBuilder.append("-----请求结束");
//            System.out.println(logBuilder.toString());
//            System.out.println("\r\n");
        }

        return "成功";
    }

    @Autowired
    IRequestCollectionService collectionService;

    @PostMapping("/setClientModel")
    @ApiOperation(value = "设置客户端模块名称", notes = "设置客户端模块名称")
    public String setClientModel (@RequestBody ClientModelConfig config) {
        if(clientModelConfig!=null)
        {
            clientModelConfig.setClientName(config.getClientName());
            clientModelConfig.setUiName(config.getUiName());
            clientModelConfig.setActionName(config.getActionName());
            clientModelConfig.setOpen(config.isOpen());
        }
        return "成功";
    }






//    @PostMapping("/collect2")
//    @ApiOperation(value = "222", notes = "222.")
//    public String collect(@RequestBody ) {
//
//        clientModelConfig.setClientName();
//
//        collectionService.save(requestCollection);
//        return "成功";
//    }

}
